package com.huitone.gddw.controller.worktable.paramconfigmanage;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.RedUserList;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.IRedUserListService;
import com.huitone.gddw.service.dto.RedUserListDTO;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 红名单用户控制器
 * @author Weiliyu
 *
 */
@Controller
@RequestMapping(value="redUserList")
public class RedUseController extends CommonController {
	
	private final static Logger LOGGER = Logger.getLogger(RedUseController.class);
	
	@Autowired
	private IRedUserListService redUserListService;
	
	/**
	 * 查询红名单用户
	 * @param page
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<RedUserListDTO> query(QueryPage<RedUserList> page, HttpServletRequest request){
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询红名单用户";
		Map<String, Object> params = new HashMap<String, Object>();
		String svrNode = request.getParameter("svrNode");
		String phone = request.getParameter("phone");
		String status = request.getParameter("status");
		params.put("svrNode", svrNode);
		params.put("phone", phone);
		params.put("status", status);
		page.setParams(params);
		QueryPage<RedUserListDTO> result = null;
		try {
			result = redUserListService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询红名单用户信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 更改状态
	 * @param recId
	 * @param status
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String recId, String status){
		try {
			RedUserList entity = redUserListService.selectByPrimaryKey(recId);
			entity.setStatus(status);
			redUserListService.changeStatus(entity);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改红名单状态过程中出现异常："+e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 保存
	 * @param entity RedUse
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	public Message save(RedUserList entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]添加红名单用户";
		boolean isSuccess = true;
		String msg;
		try {
			List<RedUserList> redUserList = redUserListService.selectByphone(entity.getPhone());
			if (redUserList.isEmpty() || redUserList.size()==0) {
				redUserListService.save(entity);
				msg = "保存成功！";
			}else {
				isSuccess = false;
				msg = "该红名单用户已存在！";
			}
		} catch (Exception e) {
			LOGGER.error("保存红名单用户信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "保存失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}

	/**
	 * 修改页面数据准备
	 * @param recId 记录ID
	 * @return RedUseDTO
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public RedUserListDTO toUpdate(String recId) {
		try {
			RedUserListDTO entity = redUserListService.toUpdate(recId);
			return entity;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return new RedUserListDTO();
		}
	}
	
	/**
	 * 更新
	 * @param entity RedUse
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(RedUserList entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改红名单用户";
		boolean isSuccess = true;
		String msg;
		try {
			RedUserList redUserList = redUserListService.selectByPrimaryKey(entity.getRecId());
			redUserList.setSvrNode(entity.getSvrNode());
			redUserList.setPhone(entity.getPhone());
			redUserList.setStatus(entity.getStatus());
			redUserList.setRemark(entity.getRemark());
			redUserListService.update(redUserList);
			msg = "修改成功！";
		} catch (Exception e) {
			LOGGER.error("修改红名单用户信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 删除
	 * @param recId 记录ID
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String recId) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除红名单用户";
		boolean isSuccess = true;
		String msg;
		try {
			redUserListService.delete(recId);
			msg = "删除成功！";
		} catch (Exception e) {
			LOGGER.error("删除红名单用户信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "红名单用户信息表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<RedUserListDTO> list = redUserListService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new RedUserListDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
}
